package com.ruoyi.system.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.Base64Utils;
import com.ruoyi.system.domain.LoginSysUserDep;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;

/**
 * 用户 业务层处理
 *
 * @author ess
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private UkLoginInfoMapper ukLoginInfoMapper;


    @Autowired
    private JmService jmService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IPersonService personService;

    @Autowired
    private ISealJurService sealJurService;

    @Autowired
    private ISealDetailService sealDetailService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IBusinessSysService businessSysService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
//        加密
        List<SysUser> sysUsers = userMapper.selectUserList(getESysUser(user));
//        解密
        if (sysUsers != null && sysUsers.size() > 0) {
            for (SysUser sysUser : sysUsers) {
                getDSysUser(sysUser);
            }
        }
        return sysUsers;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {

        //        加密
        List<SysUser> sysUsers = userMapper.selectAllocatedList(getESysUser(user));
        //        解密
        if (sysUsers != null && sysUsers.size() > 0) {
            for (SysUser sysUser : sysUsers) {
                getDSysUser(sysUser);
            }
        }
        return sysUsers;
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        //        加密
        List<SysUser> sysUsers = userMapper.selectUnallocatedList(getESysUser(user));
        //        解密
        if (sysUsers != null && sysUsers.size() > 0) {
            for (SysUser sysUser : sysUsers) {
                getDSysUser(sysUser);
            }
        }
        return sysUsers;
    }

//    /**
//     * 通过用户名查询用户
//     *
//     * @param userName 用户名
//     * @return 用户对象信息
//     */
//    @Override
//    public SysUser selectUserByUserName(String userName) {
////        加密
//        String userNameE = jmService.getEncryptString(userName);
//        SysUser sysUser = userMapper.selectUserByUserName(userNameE);
////        解密
//        return getDSysUser(sysUser);
//    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
//        解密
        return getDSysUser(userMapper.selectUserById(userId));
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户id
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId) {

        List<SysRole> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        //        加密
        String userNameE = jmService.getEncryptString(userName);
        List<SysPost> list = postMapper.selectPostsByUserName(userNameE);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

//    /**
//     * 校验用户名称是否唯一
//     *
//     * @param userName 用户名称
//     * @return 结果
//     */
//    @Override
//    public String checkUserNameUnique(String userName) {
//        //        加密
//        String userNameE = jmService.getEncryptString(userName);
//        int count = userMapper.checkUserNameUnique(userNameE);
//        if (count > 0) {
//            return UserConstants.NOT_UNIQUE;
//        }
//        return UserConstants.UNIQUE;
//    }

    /**
     * 校验用户手机号是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
////        用户名称防止重名 拼接单位id
//        user.setUserName(user.getUserName() + user.getDeptId());

//        加密
        SysUser sysUserE = getESysUser(user);
        // 新增用户信息
        int rows = userMapper.insertUser(sysUserE);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);

//        判断是否有上传证书 有的话需要添加登录证书表信息
        if (user.getTempFile() != null && !"".equals(user.getTempFile())) {
//           将此路径下的证书文件转换成Base64字符串保存在数据库中
            String filePath = RuoYiConfig.getUploadPath();
            String cerFileParh = filePath + user.getTempFile();
            try {
                File cerFile = new File(cerFileParh);
                if (cerFile.exists()) {
                    UkLoginInfo ukLoginInfo = ukLoginInfoMapper.selectUkLoginInfoByPersonId(user.getPersonId());
                    if (ukLoginInfo != null) {
                        ukLoginInfo.setUkCert(Base64Utils.encodeBase64File(cerFileParh));
                        ukLoginInfoMapper.updateUkLoginInfo(ukLoginInfo);
                    } else {
                        UkLoginInfo loginInfo = new UkLoginInfo();
                        loginInfo.setPersonId(user.getPersonId());
                        loginInfo.setuState(0);
                        loginInfo.setUkCert(Base64Utils.encodeBase64File(cerFileParh));
                        ukLoginInfoMapper.insertUkLoginInfo(loginInfo);
                    }

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return rows;
    }

//    /**
//     * 注册用户信息
//     *
//     * @param user 用户信息
//     * @return 结果
//     */
//    @Override
//    public boolean registerUser(SysUser user) {
//        //        加密
//        SysUser sysUserE = getESysUser(user);
//        return userMapper.insertUser(sysUserE) > 0;
//    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
////        用户名称防止重名 拼接单位id
//        user.setUserName(user.getUserName() + user.getDeptId());

        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);

//        判断uk登录证书是否有值  有的话进行修改
        if (user.getTempFile() != null && !"".equals(user.getTempFile())) {
//           将此路径下的证书文件转换成Base64字符串保存在数据库中
            String filePath = RuoYiConfig.getUploadPath();
            String cerFileParh = filePath + user.getTempFile();
            try {
                File cerFile = new File(cerFileParh);
                if (cerFile.exists()) {
                    UkLoginInfo loginInfo = new UkLoginInfo();
                    loginInfo.setPersonId(user.getPersonId());
                    loginInfo.setUkCert(Base64Utils.encodeBase64File(cerFileParh));
                    ukLoginInfoMapper.updateUkLoginInfo(loginInfo);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //        加密
        SysUser sysUserE = getESysUser(user);
        return userMapper.updateUser(sysUserE);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        //        加密
        SysUser sysUserE = getESysUser(user);
        return userMapper.updateUser(sysUserE);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        //        加密
        SysUser sysUserE = getESysUser(user);
        return userMapper.updateUser(sysUserE);
    }

    /**
     * 修改用户头像
     *
     * @param avatar 头像base64
     * @param userId 部门id
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        return userMapper.updateUserAvatar(userId, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
//        加密
        return userMapper.updateUser(getESysUser(user));
    }

//    /**
//     * 重置用户密码
//     *
//     * @param userName 用户名
//     * @param password 密码
//     * @return 结果
//     */
//    @Override
//    public int resetUserPwd(String userName, String password) {
////        加密
//        String userNameE = jmService.getEncryptString(userName);
//        String passwordE = jmService.getEncryptString(password);
//        return userMapper.resetUserPwd(userNameE, passwordE);
//    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotNull(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);

        SysUser sysUser = userService.selectUserById(userId);
        List<SysUser> sysUserList = userService.selectUserByPersonIdIsNotDelete(sysUser.getPersonId());
        if (sysUserList != null && sysUserList.size() == 1) {
            ukLoginInfoMapper.deleteUkLoginInfoByPersonId(sysUser.getPersonId());
            //删除此用户的在用授权信息 不包含授权他人的
            sealJurService.deleteSealJurBySealPersonId(sysUser.getPersonId());

//            删除ukey登录信息 20220510
            ukLoginInfoMapper.deleteUkLoginInfoByPersonId(sysUser.getPersonId());
        }



        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);

        // 删除此用户的授权 转授信息  先判断其它单位没有此personId的用户
        for (Long userId : userIds) {
            SysUser sysUser = userService.selectUserById(userId);
            List<SysUser> sysUserList = userService.selectUserByPersonIdIsNotDelete(sysUser.getPersonId());
            if (sysUserList != null && sysUserList.size() == 1) {

                ukLoginInfoMapper.deleteUkLoginInfoByPersonId(sysUser.getPersonId());
                //删除此用户的在用授权信息 不包含授权他人的
                sealJurService.deleteSealJurBySealPersonId(sysUser.getPersonId());

                //            删除ukey登录信息   20220510
                ukLoginInfoMapper.deleteUkLoginInfoByPersonId(sysUser.getPersonId());
            }
        }

        return userMapper.deleteUserByIds(userIds);
    }

//    /**
//     * 导入用户数据
//     *
//     * @param userList        用户数据列表
//     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
//     * @param operName        操作用户
//     * @return 结果
//     */
//    @Override
//    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
//        if (StringUtils.isNull(userList) || userList.size() == 0) {
//            throw new ServiceException("导入用户数据不能为空！");
//        }
////        加密
//        for (SysUser sysUser : userList) {
//            getESysUser(sysUser);
//        }
//
//        int successNum = 0;
//        int failureNum = 0;
//        StringBuilder successMsg = new StringBuilder();
//        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
//        for (SysUser user : userList) {
//            try {
//                // 验证是否存在这个用户
//                SysUser u = userMapper.selectUserByUserName(user.getUserName());
//                if (StringUtils.isNull(u)) {
//                    user.setPassword(jmService.getEncryptString(SecurityUtils.encryptPassword(password)));
//                    user.setCreateBy(operName);
//                    this.insertUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
//                } else if (isUpdateSupport) {
//                    user.setUpdateBy(operName);
//                    this.updateUser(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
//                } else {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
//                }
//            } catch (Exception e) {
//                failureNum++;
//                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
//                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
//            }
//        }
//        if (failureNum > 0) {
//            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new ServiceException(failureMsg.toString());
//        } else {
//            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
//        }
//        return successMsg.toString();
//    }


    /**
     * 通过用户名和单位id查询用户
     *
     * @param username 用户名
     * @param depId    单位id
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserNameAndDepId(String username, String depId) {
        //        加密
        String userNameE = jmService.getEncryptString(username);
        SysUser sysUser = null;
        if (depId.contains("-")) {
            String[] userDepIdAndBirNumArr = depId.split("-");
            sysUser = userMapper.selectUserByUserNameAndDepIdAndBirNum(userNameE, Integer.valueOf(userDepIdAndBirNumArr[0]), jmService.getEncryptString(userDepIdAndBirNumArr[1]));
        } else {
            sysUser = userMapper.selectUserByUserNameAndDepId(userNameE, Integer.valueOf(depId));
        }

//        解密
        return getDSysUser(sysUser);
    }


    /**
     * 根据姓名查询单位列表 登录处
     *
     * @param userName 用户姓名
     * @return
     */
    @Override
    public List<LoginSysUserDep> selectDepListByUserName(String userName) {
//        加密
        String userNameE = jmService.getEncryptString(userName);
        List<LoginSysUserDep> loginSysUserDeps = userMapper.selectDepListByUserName(userNameE);

        if (loginSysUserDeps != null && loginSysUserDeps.size() > 0) {
//            只有一个时不返回生日
            if (loginSysUserDeps.size() == 1) {
                for (LoginSysUserDep lo : loginSysUserDeps) {
//                解密
                    lo.setUserName(jmService.getDecryptString(lo.getUserName()));
                    lo.setBirNum(null);
//                查询单位名称
                    if (lo.getTypeCode() == 2) {
                        SysDept sysDept = sysDeptService.selectDeptById(lo.getDepId());
                        SysDept parentUnit = sysDeptService.selectDeptById(Long.valueOf(sysDept.getAncestors().split(",")[3]));
                        lo.setDepName(parentUnit.getDeptName() + "-" + lo.getDepName());
                    }

                }

            } else {
//                重名时返回生日 便于登录人区分
                for (LoginSysUserDep lo : loginSysUserDeps) {
//                解密
                    lo.setUserName(jmService.getDecryptString(lo.getUserName()));
                    lo.setBirNum(jmService.getDecryptString(lo.getBirNum()));
//                查询单位名称
                    if (lo.getTypeCode() == 2) {
                        SysDept sysDept = sysDeptService.selectDeptById(lo.getDepId());
                        SysDept parentUnit = sysDeptService.selectDeptById(Long.valueOf(sysDept.getAncestors().split(",")[3]));
                        lo.setDepName(parentUnit.getDeptName() + "-" + lo.getDepName());
                    }else {
                        lo.setDepName(lo.getDepName() + "-" + lo.getBirNum());
                    }


                }
            }

        }

        return loginSysUserDeps;
    }

    /**
     * 检查此单位下是否已经此用户
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public Integer checkUserIsExist(SysUser user) {
        //加密
        return userMapper.checkUserIsExistByPersonIdAndUserNameAndDepId(jmService.getEncryptString(user.getUserName()), user.getPersonId(), user.getDeptId());
    }

    /**
     * 修改基础人员的登录账号 也修改用户姓名 保持一致
     *
     * @param person
     * @return
     */
    @Override
    public Integer updateUserNameByPersonId(Person person) {
//        person已加密
        return userMapper.updateUserNameByPersonId(person);
    }

    /**
     * 查询签章用户列表
     *
     * @param user
     * @return
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectSignUserList(SysUser user) {
        if (user.getSignJurState() != null) {
            if (user.getSignJurState() == 2) {
                List<SysUser> sysUsersTwo = userMapper.selectSignUserTwoList(getESysUser(user));
//        解密
                if (sysUsersTwo != null && sysUsersTwo.size() > 0) {
                    for (SysUser sysUser : sysUsersTwo) {
                        getDSysUser(sysUser);

                        //                判断是否已授权手签
                        SealJur sealJur = new SealJur();
                        sealJur.setSealPersonId(sysUser.getPersonId());
                        sealJur.setSealOrHw(0L);
                        List<SealJur> sealJurs = sealJurService.selectSealJurList(sealJur);
                        if (sealJurs == null || sealJurs.size() == 0) {
                            sysUser.setIsHaveSignJur(1L);
                        } else {
                            //                查找所有业务系统
                            Integer num = 0;
                            BusinessSys businessSys = new BusinessSys();
                            List<BusinessSys> businessSysList = businessSysService.selectBusinessSysList(businessSys);
                            if (businessSysList != null && businessSysList.size() > 0) {
                                for (BusinessSys sys : businessSysList) {
                                    sealJur.setBusinessSysIds(sys.getbSysId());
                                    List<SealJur> sealJursys = sealJurService.selectSealJurList(sealJur);
                                    if (sealJursys != null && sealJursys.size() > 0) {
                                        num += 1;
                                    }
                                }
                            }

                            if (num == businessSysList.size()) {
                                sysUser.setIsHaveSignJur(0L);
                            } else {
                                sysUser.setIsHaveSignJur(3L);
                            }
                        }

//                    判断是否已制作手签
                        SealDetail sDetail = new SealDetail();
                        sDetail.setSealTypeId("ESS001");
                        sDetail.setSealPersonId(sysUser.getPersonId());
                        List<SealDetail> sealDetails = sealDetailService.selectSealDetailList(sDetail);
                        if (sealDetails != null && sealDetails.size() > 0) {
                            sysUser.setIsHaveSign(0L);
                        } else {
                            sysUser.setIsHaveSign(1L);
                        }

//                判断手签状态
                        if (sysUser.getIsHaveSign() == 1L) {
                            sysUser.setSignJurState(2L);
                        } else if (sysUser.getIsHaveSign() == 0L && sysUser.getIsHaveSignJur() == 0L) {
                            sysUser.setSignJurState(0L);
                        } else if (sysUser.getIsHaveSignJur() == 3L) {
                            sysUser.setSignJurState(3L);
                        } else {
                            sysUser.setSignJurState(1L);
                        }

                    }
                }

                return sysUsersTwo;

            } else if (user.getSignJurState() == 1) {
                List<SysUser> sysUsersOne = userMapper.selectSignUserOneList(getESysUser(user));
//        解密
                if (sysUsersOne != null && sysUsersOne.size() > 0) {
                    for (SysUser sysUser : sysUsersOne) {
                        getDSysUser(sysUser);

                        //                判断是否已授权手签
                        SealJur sealJur = new SealJur();
                        sealJur.setSealPersonId(sysUser.getPersonId());
                        sealJur.setSealOrHw(0L);
                        List<SealJur> sealJurs = sealJurService.selectSealJurList(sealJur);
                        if (sealJurs == null || sealJurs.size() == 0) {
                            sysUser.setIsHaveSignJur(1L);
                        } else {
                            //                查找所有业务系统
                            Integer num = 0;
                            BusinessSys businessSys = new BusinessSys();
                            List<BusinessSys> businessSysList = businessSysService.selectBusinessSysList(businessSys);
                            if (businessSysList != null && businessSysList.size() > 0) {
                                for (BusinessSys sys : businessSysList) {
                                    sealJur.setBusinessSysIds(sys.getbSysId());
                                    List<SealJur> sealJursys = sealJurService.selectSealJurList(sealJur);
                                    if (sealJursys != null && sealJursys.size() > 0) {
                                        num += 1;
                                    }
                                }
                            }

                            if (num == businessSysList.size()) {
                                sysUser.setIsHaveSignJur(0L);
                            } else {
                                sysUser.setIsHaveSignJur(3L);
                            }
                        }

//                    判断是否已制作手签
                        SealDetail sDetail = new SealDetail();
                        sDetail.setSealTypeId("ESS001");
                        sDetail.setSealPersonId(sysUser.getPersonId());
                        List<SealDetail> sealDetails = sealDetailService.selectSealDetailList(sDetail);
                        if (sealDetails != null && sealDetails.size() > 0) {
                            sysUser.setIsHaveSign(0L);
                        } else {
                            sysUser.setIsHaveSign(1L);
                        }

//                判断手签状态
                        if (sysUser.getIsHaveSign() == 1L) {
                            sysUser.setSignJurState(2L);
                        } else if (sysUser.getIsHaveSign() == 0L && sysUser.getIsHaveSignJur() == 0L) {
                            sysUser.setSignJurState(0L);
                        } else if (sysUser.getIsHaveSignJur() == 3L) {
                            sysUser.setSignJurState(3L);
                        } else {
                            sysUser.setSignJurState(1L);
                        }

                    }
                }

                return sysUsersOne;
            } else {
                List<SysUser> sysUsersZero = userMapper.selectSignUserZeroList(getESysUser(user));
//        解密
                if (sysUsersZero != null && sysUsersZero.size() > 0) {
                    for (SysUser sysUser : sysUsersZero) {
                        getDSysUser(sysUser);

                        //                判断是否已授权手签
                        SealJur sealJur = new SealJur();
                        sealJur.setSealPersonId(sysUser.getPersonId());
                        sealJur.setSealOrHw(0L);
                        List<SealJur> sealJurs = sealJurService.selectSealJurList(sealJur);
                        if (sealJurs == null || sealJurs.size() == 0) {
                            sysUser.setIsHaveSignJur(1L);
                        } else {
                            //                查找所有业务系统
                            Integer num = 0;
                            BusinessSys businessSys = new BusinessSys();
                            List<BusinessSys> businessSysList = businessSysService.selectBusinessSysList(businessSys);
                            if (businessSysList != null && businessSysList.size() > 0) {
                                for (BusinessSys sys : businessSysList) {
                                    sealJur.setBusinessSysIds(sys.getbSysId());
                                    List<SealJur> sealJursys = sealJurService.selectSealJurList(sealJur);
                                    if (sealJursys != null && sealJursys.size() > 0) {
                                        num += 1;
                                    }
                                }
                            }

                            if (num == businessSysList.size()) {
                                sysUser.setIsHaveSignJur(0L);
                            } else {
                                sysUser.setIsHaveSignJur(3L);
                            }
                        }

//                    判断是否已制作手签
                        SealDetail sDetail = new SealDetail();
                        sDetail.setSealTypeId("ESS001");
                        sDetail.setSealPersonId(sysUser.getPersonId());
                        List<SealDetail> sealDetails = sealDetailService.selectSealDetailList(sDetail);
                        if (sealDetails != null && sealDetails.size() > 0) {
                            sysUser.setIsHaveSign(0L);
                        } else {
                            sysUser.setIsHaveSign(1L);
                        }

//                判断手签状态
                        if (sysUser.getIsHaveSign() == 1L) {
                            sysUser.setSignJurState(2L);
                        } else if (sysUser.getIsHaveSign() == 0L && sysUser.getIsHaveSignJur() == 0L) {
                            sysUser.setSignJurState(0L);
                        } else if (sysUser.getIsHaveSignJur() == 3L) {
                            sysUser.setSignJurState(3L);
                        } else {
                            sysUser.setSignJurState(1L);
                        }

                    }
                }

                return sysUsersZero;


            }

        }

//        加密
        List<SysUser> sysUsers = userMapper.selectSignUserList(getESysUser(user));
//        解密
        if (sysUsers != null && sysUsers.size() > 0) {
            for (SysUser sysUser : sysUsers) {
                getDSysUser(sysUser);

                //                判断是否已授权手签
                SealJur sealJur = new SealJur();
                sealJur.setSealPersonId(sysUser.getPersonId());
                sealJur.setSealOrHw(0L);
                List<SealJur> sealJurs = sealJurService.selectSealJurList(sealJur);
                if (sealJurs == null || sealJurs.size() == 0) {
                    sysUser.setIsHaveSignJur(1L);
                } else {
                    //                查找所有业务系统
                    Integer num = 0;
                    BusinessSys businessSys = new BusinessSys();
                    List<BusinessSys> businessSysList = businessSysService.selectBusinessSysList(businessSys);
                    if (businessSysList != null && businessSysList.size() > 0) {
                        for (BusinessSys sys : businessSysList) {
                            sealJur.setBusinessSysIds(sys.getbSysId());
                            List<SealJur> sealJursys = sealJurService.selectSealJurList(sealJur);
                            if (sealJursys != null && sealJursys.size() > 0) {
                                num += 1;
                            }
                        }
                    }

                    if (num == businessSysList.size()) {
                        sysUser.setIsHaveSignJur(0L);
                    } else {
                        sysUser.setIsHaveSignJur(3L);
                    }
                }

//                    判断是否已制作手签
                SealDetail sDetail = new SealDetail();
                sDetail.setSealTypeId("ESS001");
                sDetail.setSealPersonId(sysUser.getPersonId());
                List<SealDetail> sealDetails = sealDetailService.selectSealDetailList(sDetail);
                if (sealDetails != null && sealDetails.size() > 0) {
                    sysUser.setIsHaveSign(0L);
                } else {
                    sysUser.setIsHaveSign(1L);
                }

//                判断手签状态
                if (sysUser.getIsHaveSign() == 1L) {
                    sysUser.setSignJurState(2L);
                } else if (sysUser.getIsHaveSign() == 0L && sysUser.getIsHaveSignJur() == 0L) {
                    sysUser.setSignJurState(0L);
                } else if (sysUser.getIsHaveSignJur() == 3L) {
                    sysUser.setSignJurState(3L);
                } else {
                    sysUser.setSignJurState(1L);
                }

            }
        }

//        手签状态查询
//            if (sysUsers != null && sysUsers.size() > 0) {
////                for (int i = 0; i < sysUsers.size(); i++) {
////                    if (sysUsers.get(i).getSignJurState() != user.getSignJurState()) {
////                        sysUsers.remove(i);
////                        i--;
////                    }
////                    }
//                for (SysUser sysUserSignState : sysUsers) {
//                    if (sysUserSignState.getSignJurState() != user.getSignJurState()) {
//                        delete(sysUserSignState, sysUsers);
//                    }
//                }
//            }

        return sysUsers;
    }


    public static List delete(Object obj, List list) {
        Iterator it = list.iterator();
        while (it.hasNext()) {
            if (it.next() == obj) {
                it.remove();
            }
        }
        return list;
    }

    /**
     * 根据personId查找未删除用户
     *
     * @param personId
     * @return
     */
    @Override
    public List<SysUser> selectUserByPersonIdIsNotDelete(String personId) {
        List<SysUser> sysUserList = userMapper.selectUserByPersonIdIsNotDelete(personId);
        if (sysUserList != null && sysUserList.size() > 0) {
            for (SysUser sysUser : sysUserList) {
                getDSysUser(sysUser);
            }
        }
        return sysUserList;
    }


    //加密
    private SysUser getESysUser(SysUser sysUser) {
        if (sysUser != null) {
            if (StringUtils.isNotEmpty(sysUser.getUserName())) {
                sysUser.setUserName(jmService.getEncryptString(sysUser.getUserName()));
            }

            if (StringUtils.isNotEmpty(sysUser.getNickName())) {
                sysUser.setNickName(jmService.getEncryptString(sysUser.getNickName()));

            }
            if (StringUtils.isNotEmpty(sysUser.getPassword())) {
                sysUser.setPassword(jmService.getEncryptString(sysUser.getPassword()));

            }
        }

        return sysUser;
    }

    //    解密
    private SysUser getDSysUser(SysUser sysUser) {
        if (sysUser != null) {
            if (StringUtils.isNotEmpty(sysUser.getUserName())) {
                sysUser.setUserName(jmService.getDecryptString(sysUser.getUserName()));
            }

            if (StringUtils.isNotEmpty(sysUser.getNickName())) {
                sysUser.setNickName(jmService.getDecryptString(sysUser.getNickName()));

            }
            if (StringUtils.isNotEmpty(sysUser.getPassword())) {
                sysUser.setPassword(jmService.getDecryptString(sysUser.getPassword()));
            }
        }
        return sysUser;
    }

}
